package com.easysettle

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.easysettle.databinding.ActivityProductManagementBinding
import com.easysettle.model.Product
import com.easysettle.service.MainService
import java.util.concurrent.Executors

/**
 * 商品管理Activity
 * 用于查看和管理所有已注册的商品信息
 */
class ProductManagementActivity : AppCompatActivity() {
    // ViewBinding实例
    private lateinit var binding: ActivityProductManagementBinding
    // 主服务实例
    private lateinit var mainService: MainService
    // 商品列表
    private lateinit var productList: MutableList<Product>
    // 商品适配器
    private lateinit var productAdapter: ProductAdapter
    // 当前搜索查询
    private var currentSearchQuery: String? = null

    companion object {
        // 日志标签
        private const val TAG = "ProductManagementActivity"
        // 编辑商品请求码
        const val EDIT_PRODUCT_REQUEST = 103
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 初始化ViewBinding
        binding = ActivityProductManagementBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        // 初始化主服务
        mainService = MainService(this)
        
        // 设置返回按钮点击事件
        binding.btnBack.setOnClickListener {
            finish()
        }
        
        // 初始化RecyclerView
        binding.recyclerViewProduct.layoutManager = LinearLayoutManager(this)
        productList = mutableListOf()
        productAdapter = ProductAdapter(productList, this::onProductClick, this::onProductDelete)
        binding.recyclerViewProduct.adapter = productAdapter
        
        // 加载商品列表
        loadProducts()
        
        // 设置刷新按钮点击事件
        binding.btnRefresh.setOnClickListener {
            // 清除搜索查询并重新加载所有商品
            currentSearchQuery = null
            binding.etSearchQuery.text?.clear()
            loadProducts()
        }
        
        // 设置搜索按钮点击事件
        binding.btnSearch.setOnClickListener {
            val query = binding.etSearchQuery.text.toString().trim()
            currentSearchQuery = query
            loadProducts()
        }
        
        // 设置输入框的回车搜索
        binding.etSearchQuery.setOnEditorActionListener {
            v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || 
                (event != null && event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER)) {
                val query = binding.etSearchQuery.text.toString().trim()
                currentSearchQuery = query
                loadProducts()
                true
            } else {
                false
            }
        }
    }

    /**
     * 加载商品列表
     */
    private fun loadProducts() {
        binding.progressBar.visibility = View.VISIBLE
        binding.recyclerViewProduct.visibility = View.GONE
        binding.tvEmptyMessage.visibility = View.GONE
        
        // 使用线程池执行后台任务
        val executorService = Executors.newSingleThreadExecutor()
        executorService.execute {
            // 根据当前搜索查询获取商品
            val products = if (currentSearchQuery.isNullOrEmpty()) {
                mainService.getAllProducts()
            } else {
                mainService.searchProducts(currentSearchQuery!!)
            }
            
            // 在主线程更新UI
            runOnUiThread {
                binding.progressBar.visibility = View.GONE
                
                // 更新商品列表
                productList.clear()
                productList.addAll(products)
                productAdapter.notifyDataSetChanged()
                
                // 显示空数据提示或商品列表
                if (productList.isEmpty()) {
                    binding.tvEmptyMessage.visibility = View.VISIBLE
                    // 根据是否有搜索查询显示不同的空数据提示
                    if (currentSearchQuery.isNullOrEmpty()) {
                        binding.tvEmptyMessage.setText(R.string.no_products_message)
                    } else {
                        binding.tvEmptyMessage.text = getString(R.string.no_search_results, currentSearchQuery)
                    }
                } else {
                    binding.recyclerViewProduct.visibility = View.VISIBLE
                }
            }
        }
    }

    /**
     * 商品点击事件处理
     */
    private fun onProductClick(product: Product) {
        // 打开商品详情页面进行编辑
        val intent = Intent(this, ProductDetailActivity::class.java)
        intent.putExtra("product", product)
        startActivityForResult(intent, EDIT_PRODUCT_REQUEST)
    }

    /**
     * 商品删除事件处理
     */
    private fun onProductDelete(product: Product) {
        // 显示确认删除对话框
        AlertDialog.Builder(this)
            .setTitle("删除商品")
            .setMessage("确定要删除商品'${product.name}'吗？")
            .setPositiveButton("确定") {
                _, _ ->
                mainService.deleteProduct(product.id) {
                    success ->
                    runOnUiThread {
                        if (success) {
                            Toast.makeText(this, "商品删除成功", Toast.LENGTH_SHORT).show()
                            loadProducts() // 重新加载商品列表
                        } else {
                            Toast.makeText(this, "商品删除失败", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 处理编辑商品的结果
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        
        if (requestCode == EDIT_PRODUCT_REQUEST && resultCode == RESULT_OK) {
            // 商品信息已更新，重新加载商品列表
            loadProducts()
        }
    }

    /**
     * 商品适配器类
     */
    inner class ProductAdapter(
        private val products: List<Product>,
        private val onProductClick: (Product) -> Unit,
        private val onProductDelete: (Product) -> Unit
    ) : RecyclerView.Adapter<ProductAdapter.ProductViewHolder>() {
        
        inner class ProductViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val binding = com.easysettle.databinding.ItemProductBinding.bind(itemView)
        }
        
        override fun onCreateViewHolder(parent: android.view.ViewGroup, viewType: Int): ProductViewHolder {
            val view = android.view.LayoutInflater.from(parent.context)
                .inflate(R.layout.item_product, parent, false)
            return ProductViewHolder(view)
        }
        
        override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
            val product = products[position]
            
            // 显示商品信息
            holder.binding.tvProductId.text = String.format("%03d", product.id?.toIntOrNull() ?: 0)
            holder.binding.tvProductName.text = product.name
            holder.binding.tvProductPrice.text = String.format("¥%.2f", product.price)
            holder.binding.tvProductBarcode.text = if (product.barcode.isEmpty()) "未设置" else product.barcode
            
            // 设置商品图片
            if (product.imagePath?.isNotEmpty() == true) {
                try {
                    product.imagePath?.let {
                        val file = java.io.File(it)
                        if (file.exists()) {
                            val bitmap = android.graphics.BitmapFactory.decodeFile(it)
                            holder.binding.ivProductImage.setImageBitmap(bitmap)
                        } else {
                            holder.binding.ivProductImage.setImageResource(R.drawable.ic_product_placeholder)
                        }
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "加载商品图片失败", e)
                    holder.binding.ivProductImage.setImageResource(R.drawable.ic_product_placeholder)
                }
            } else {
                holder.binding.ivProductImage.setImageResource(R.drawable.ic_product_placeholder)
            }
            
            // 设置点击事件
            holder.itemView.setOnClickListener {
                onProductClick(product)
            }
            
            // 设置删除按钮点击事件
            holder.binding.btnDeleteProduct.setOnClickListener {
                onProductDelete(product)
            }
        }
        
        override fun getItemCount(): Int {
            return products.size
        }
    }
}